package address

import (
	"context"
	"fmt"
	"net/http"

	"google.golang.org/grpc/status"

	"gitee.com/enjoy_5/enjoy-wallet/internal/server"
	"gitee.com/enjoy_5/enjoy-wallet/model/address"
	address2 "gitee.com/enjoy_5/enjoy-wallet/proto/address"
)

type AddressService struct {
	address2.UnimplementedAddressServer
}

func (a AddressService) CreateAddress(ctx context.Context, in *address2.CreateAddressRequest) (*address2.CreateAddressResponse, error) {
	if in.GetIn().GetUserid() == 0 {
		return nil, status.Errorf(http.StatusInternalServerError, "id is required")
	}

	if len(in.GetIn().GetMobile()) != 11 && in.GetIn().GetMobile() != "" {
		return nil, status.Errorf(http.StatusInternalServerError, "mobile is invalid")
	}

	info, err := server.CreateAddress(in.GetIn())
	if err != nil {
		return nil, status.Errorf(http.StatusInternalServerError, err.Error())
	}

	return &address2.CreateAddressResponse{
		Info: info,
	}, nil
}

func (a AddressService) UpdateAddress(ctx context.Context, in *address2.UpdateAddressRequest) (*address2.UpdateAddressResponse, error) {
	if len(in.GetIn().GetMobile()) != 11 && in.GetIn().GetMobile() != "" {
		return nil, status.Errorf(http.StatusInternalServerError, "mobile is invalid")
	}

	info, err := server.UpdateAddress(in.GetIn())
	if err != nil {
		return nil, status.Errorf(http.StatusInternalServerError, err.Error())
	}

	return &address2.UpdateAddressResponse{
		Info: info,
	}, nil
}

func (a AddressService) DeleteAddress(ctx context.Context, in *address2.DeleteAddressRequest) (*address2.DeleteAddressResponse, error) {
	if in.GetUserID() == 0 {
		return nil, status.Errorf(http.StatusInternalServerError, "id is required")
	}

	err := server.DeleteAddress(in)
	if err != nil {
		return nil, status.Errorf(http.StatusInternalServerError, err.Error())
	}

	return &address2.DeleteAddressResponse{}, nil
}

func (a AddressService) SearchAddress(ctx context.Context, in *address2.SearchAddressRequest) (resp *address2.SearchAddressResponse, err error) {
	if in.Limit > 10000 {
		return nil, status.Errorf(http.StatusInternalServerError, "查询数据必须小于10000条", nil)
	}

	limit, offset, err := address.SearchAddress(int(in.Offset), int(in.Limit))
	if err != nil {
		return nil, status.Errorf(http.StatusInternalServerError, err.Error())
	}

	var info []*address2.AddressInfo

	for _, v := range limit {
		info = append(info, &address2.AddressInfo{
			Userid:          v.UserID,
			ConsigneeName:   v.ConsigneeName,
			Mobile:          v.Mobile,
			Area:            v.Area,
			DetailedAddress: v.DetailedAddress,
			Tag:             address2.TagType(v.Tag),
			DefaultAddress:  v.DefaultAddress,
		})
	}
	fmt.Println(info)
	return &address2.SearchAddressResponse{
		Infos: info,
		Total: offset,
	}, nil
}
